package com.joker.dynamic.thread.pool.sdk.trigger.listener;

import com.joker.dynamic.thread.pool.sdk.domain.IDynamicThreadPoolService;
import com.joker.dynamic.thread.pool.sdk.domain.model.entity.ThreadPoolConfigEntity;
import com.joker.dynamic.thread.pool.sdk.register.IRegistry;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.listener.MessageListener;

import java.util.List;

/**
 * 动态线程池监听器，用于监听修改 redis 配置
 * Created By guzq on 2024/10/20
 */
@Slf4j
public class ThreadPoolConfigAdjustListener implements MessageListener<ThreadPoolConfigEntity> {

    private final IDynamicThreadPoolService dynamicThreadPoolService;

    private final IRegistry registry;


    public ThreadPoolConfigAdjustListener(IDynamicThreadPoolService dynamicThreadPoolService, IRegistry registry) {
        this.dynamicThreadPoolService = dynamicThreadPoolService;
        this.registry = registry;
    }
    @Override
    public void onMessage(CharSequence charSequence, ThreadPoolConfigEntity threadPoolConfigEntity) {
        // 修改线程池配置
        log.info("修改线程池配置 poolName:{}", threadPoolConfigEntity.getThreadPoolName());
        dynamicThreadPoolService.updateThreadPoolConfig(threadPoolConfigEntity);
        // 重新上报
        log.info("重新上报线程池信息");
        List<ThreadPoolConfigEntity> threadPoolConfigEntities = dynamicThreadPoolService.queryThreadPoolConfigList();
        registry.reportThreadPool(threadPoolConfigEntities);

        ThreadPoolConfigEntity poolConfigEntity = dynamicThreadPoolService.queryThreadPoolConfigByName(threadPoolConfigEntity.getThreadPoolName());
        registry.reportThreadPoolConfigParameter(poolConfigEntity);
    }
}
